﻿using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Cobalt.Framework
{

	public abstract class SharedResource
	{
		public abstract void GetValue( Action<object> fixup );
	}

	public sealed class SharedResource<T> : SharedResource
	{
		private bool hasReadValue;
		private T value;
		private Action<T> fixup;

		internal void ResourceLoadedCallback( T value )
		{
			hasReadValue = true;
			this.value = value;

			if( fixup != null )
			{
				fixup( value );
				fixup = null;
			}
		}

		public void GetValue( Action<T> fixup )
		{
			if( fixup == null )
				return;

			if( hasReadValue )
			{
				fixup( value );
				return;
			}

			this.fixup = (Action<T>)Action<T>.Combine( this.fixup, fixup );
		}

		public override void GetValue( Action<object> fixup )
		{
			if( fixup == null )
				return;

			GetValue( (Action<T>)(o => fixup( o )) );
		}
	}

	internal sealed class SharedResourceReader<T> : ContentTypeReader<SharedResource<T>>
	{
		protected override SharedResource<T> Read( ContentReader input, SharedResource<T> existingInstance )
		{
			SharedResource<T> ret = new SharedResource<T>();
			input.ReadSharedResource<T>( ret.ResourceLoadedCallback );
			return ret;
		}
	}

}